package com.huaqin.salestracker;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.huaqin.common.Util;
import com.huaqin.customer.ConditionManger;
import com.huaqin.customer.Confirm;
import com.huaqin.customer.CustomerInformation;
import com.huaqin.customer.MessageManager;
import com.huaqin.customer.SendFeedback;
import com.huaqin.customer.SendRetry;
import com.huaqin.customer.Trigger;
import com.huaqin.customer.expansion.FunctionConfig;

import android.content.Context;
import android.util.Log;

public class SalesTrackerConfiguration {
	
	private static final String TAG = "STConfiguration";
	private XmlPullParser mParser = null;
	private Context mContext = null;
	private int eventType = -1;
	private int mConNum = 0;
	
	private boolean isDebugMode = false;
	private String mSalesSystemInfo = null;
	private CustomerInformation mCustomerInformation = null;
	private ConditionManger mConditionManger = null;
	private MessageManager mMessageManager = null;
	private Trigger mTrigger = null;

	public Confirm mConfirm = null;  //congirm config before send
	public SendRetry mSendRetry = null; //config send failed
	public SendFeedback mSendFeedback = null; //config send success
	public ArrayList<HashMap<String, Object>> mConfigItemList = null;

	public SalesTrackerConfiguration(Context context) throws XmlPullParserException{
		final XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		mContext = context;
		mParser = factory.newPullParser();
	}
	
	public boolean isSystemDebugMode(){
		return isDebugMode;
	}

	public boolean parseXMLFile(String FileName){
	    boolean result = false;
		
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(FileName);
			if(fin != null){
			    result = parse(new BufferedInputStream(fin));
			}
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, "ParseXMLFile FileNotFoundException");
		}
		catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "ParseXMLFile Exception");
		}

		return result;
	}

	public boolean parse(InputStream is) throws Exception {

		boolean result = false;
		if(is == null){
			Log.e(TAG, "InputStream is null!");
			return false;
		}
 
    	mParser.setInput(is, "UTF-8");

		eventType = mParser.getEventType();
		boolean isReadConfigStart = false;
		String conditionClassName = null;
		String conditionKey = null;
		String conditionOperator = null;
		String conditionValues = null;

		while (eventType != XmlPullParser.END_DOCUMENT) {
			
//			String currentLable = mParser.getName(); //Release for debug

			switch (eventType) {
				
				case XmlPullParser.START_DOCUMENT:
					Log.d(TAG, "======= xml file parser start! =======");
					break;
					
				case XmlPullParser.START_TAG:

					if(extractXmlValue("Debug", true)){
					    isDebugMode = (mParser.getText().equals("1") ||
								  mParser.getText().equalsIgnoreCase("On") ||
								  mParser.getText().equalsIgnoreCase("true"));
					}
					
					if(extractXmlValue("App", true)){
						mSalesSystemInfo = mParser.getText();
					}
					
					//Custom general read
					if(extractXmlValue("General", false)){
						mCustomerInformation = new CustomerInformation();
					}
					else if(extractXmlValue("Model", true)){
						mCustomerInformation.setModel(mParser.getText());
					}
					else if(extractXmlValue("Product", true)){
						mCustomerInformation.setProduct(mParser.getText());
					}
					else if(extractXmlValue("Platform", true)){ 
						mCustomerInformation.setPlatform(mParser.getText());
					}			
					
					//condition read
					if(extractXmlValue("SendCondition", false)){
						mConditionManger = new ConditionManger();
					}
					else if(extractXmlValue("Trigger", false)){
						mTrigger = new Trigger();
					}
					else if(extractXmlValue("ConditionConfig",true)){
						mTrigger.setTigger(mParser.getText());
					}
					else if(extractXmlValue("Condition", false)){
						if(!isReadConfigStart){
							isReadConfigStart = true;
						}
					}
					else if(isReadConfigStart && extractXmlValue("ClassName", true)){
						conditionClassName = mParser.getText();
					}
					else if(isReadConfigStart && extractXmlValue("Key", true)){
						conditionKey = mParser.getText();
					}					
					else if(isReadConfigStart && extractXmlValue("Operator", true)){
						conditionOperator = mParser.getText();
					}
					else if(isReadConfigStart && extractXmlValue("Value", true)){
						conditionValues = mParser.getText();
					}
					
					if(extractXmlValue("Messages", false)){
						mMessageManager =  new MessageManager();
					}
					else if(extractXmlValue("MessagesConfig", true)){
						mMessageManager.setMessageName(mParser.getText());
					}
					else if(extractXmlValue("MessagesParam", false)){
						isReadConfigStart = true;
					}
					else if(isReadConfigStart && extractXmlValue("Param", true)){
						mMessageManager.addMessageParam( mParser.getText());
					}
					else if(extractXmlValue("Address", true)){
						mMessageManager.setMessageSendAddress(mParser.getText());
					}
					else if(extractXmlValue("SMSSendMode", true)){
						mMessageManager.setSMSSendMode(mParser.getText());
					}
					
					if(extractXmlValue("Confirm", false)){
						mConfirm = new Confirm();
					}
					else if(extractXmlValue("ConfirmSwitch", true)){
						mConfirm.setConfirmSwitch(mParser.getText().equals("1") || 
								  mParser.getText().equalsIgnoreCase("On") ||
								  mParser.getText().equalsIgnoreCase("true"));
					}					
					else if(extractXmlValue("ConfirmType", true)){
						mConfirm.setConfirmType(mParser.getText());
					}
					else if(extractXmlValue("ConfirmTitle", true)){
						mConfirm.setConfirmTitle(mParser.getText());
					}
					else if(extractXmlValue("ConfirmMsg", true)){
						mConfirm.setConfirmMsg(mParser.getText());
					}
					else if(extractXmlValue("HintSuccessSwitch", true)){
						mConfirm.setHintSuccessSwitch(mParser.getText().equals("1") || 
												  mParser.getText().equalsIgnoreCase("On") ||
												  mParser.getText().equalsIgnoreCase("true"));
					}
					else if(extractXmlValue("HintType", true)){
						mConfirm.setHintSuccessType(mParser.getText());
					}
					else if(extractXmlValue("HintSuccessTitle", true)){
						mConfirm.setHintSuccessTitle(mParser.getText());
					}
					else if(extractXmlValue("HintSuccessMsg", true)){
						mConfirm.setHintSuccessMsg(mParser.getText());
					}
					
					if(extractXmlValue("RetryConfig", false)){
						mSendRetry = new SendRetry();
					}
					else if(extractXmlValue("RetrySwitch", true)){
						mSendRetry.setRetrySwitch(mParser.getText().equals("1") || 
								  mParser.getText().equalsIgnoreCase("On") ||
								  mParser.getText().equalsIgnoreCase("true"));
					}
					else if(extractXmlValue("RetryInterval", true)){
						mSendRetry.setRetryInterval(Long.valueOf(mParser.getText()));
					}
					else if(extractXmlValue("RetryTime", true)){
						mSendRetry.setRetryTime(Integer.parseInt(mParser.getText()));
					}
					
					if(extractXmlValue("Feedback", false)){
						mSendFeedback = new SendFeedback();
					}
					else if(extractXmlValue("FeedbackSwitch", true)){
						mSendFeedback.setFeedback(mParser.getText().equals("1") || 
								  mParser.getText().equalsIgnoreCase("On") ||
								  mParser.getText().equalsIgnoreCase("true"));
					}
					else if(extractXmlValue("FeedbackInterval", true)){
						mSendFeedback.setFeedbackInterval(Long.valueOf(mParser.getText()));
					}
					else if(extractXmlValue("FeedbackTime", true)){
						mSendFeedback.setFeedbackTime(Integer.parseInt(mParser.getText()));
					}
					else if(extractXmlValue("FeedbackMsg", true)){
						mSendFeedback.setFeedbackMsg(mParser.getText());
					}

					if(extractXmlValue("Title", true)){
						FunctionConfig.setDialogTitle(mParser.getText());
					}
					else if(extractXmlValue("DialogMessageConfig", true)){
						FunctionConfig.setDialogMsgConfig(mParser.getText());
					}
					else if(extractXmlValue("DialogMessage", false)){
						isReadConfigStart = true;
					}
					else if(isReadConfigStart && extractXmlValue("DialogMessageParam", true)){
						FunctionConfig.addConfigItem(mParser.getText());
					}

					break;
					
				case XmlPullParser.END_TAG:

					if(isReadConfigStart && extractXmlValue("Condition", false)){
						result = mTrigger.addCondition(conditionClassName, conditionKey, conditionOperator, conditionValues);
						isReadConfigStart = false;
						
						Util.setStringPref(mContext, ("Condition" + mConNum++), 
						        conditionClassName + " " + conditionKey + " " + conditionOperator + " " + conditionValues);
					}
					
					if(extractXmlValue("Trigger", false)){
						mConditionManger.addTrigger(mTrigger);
					}

					if(extractXmlValue("MessagesParam", false)){
						isReadConfigStart = false;
					}
					
					if(extractXmlValue("DialogMessagee", false)){
						isReadConfigStart = false;
					}
					
					break;
					
				default:
					break;
			}

			eventType = mParser.next();
		}
		
		Log.d(TAG, "======= xml parser end ======= ");
		
		return result;
	}

    //next: true - extra values 
    private boolean extractXmlValue(String Key, boolean extractVuales) throws XmlPullParserException, IOException{
    	String item = mParser.getName();

    	if(extractVuales){
    		if(Key.equalsIgnoreCase(mParser.getName())){
    			
    			eventType = mParser.next();
    			
    			String values = mParser.getText();
    		    HashMap<String, Object> Item = new HashMap<String, Object>();
    			Item.put("item", item); 
    			Item.put("value", values);

    			if(mConfigItemList == null){
    				mConfigItemList = new ArrayList<HashMap<String, Object>>();
    			}

    			mConfigItemList.add(Item);

    			Log.i(TAG, item +  " ==> " + values);
    			return true;
    		}
    	}
    	else{
    		return Key.equalsIgnoreCase(mParser.getName());
    	}
    	
    	return false;
    }
    
    public ArrayList<HashMap<String, Object>> getListViewItem(){
    	return mConfigItemList;
    }
    
    public String getSystemInfo(){
    	return mSalesSystemInfo != null ? mSalesSystemInfo : null;
    }
    
    public CustomerInformation getCustomerInformation(){
    	return mCustomerInformation != null ? mCustomerInformation : null;
    }
	
    public ConditionManger getConditionManger(){
    	return mConditionManger != null ? mConditionManger : null;
    }
    
    public MessageManager getMessageManager(){
    	return mMessageManager != null ? mMessageManager : null;
    }
}
	

